class Solution {
public:
    void reform(string& str, TreeNode* root)
    {
        if (root == nullptr)
            return;

        str += to_string(root->val);
        if (!root->left && root->right)
            str += "()";

        if (root->left)
            str += '(';
        reform(str, root->left);
        if (root->left)
            str += ')';

        if (root->right)
            str += '(';
        reform(str, root->right);
        if (root->right)
            str += ')';

    }

    string tree2str(TreeNode* root)
    {

        string str;
        reform(str, root);

        return str;
    }
};
